package com.easylinkin.linkappapi.blockqueue;

import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * @author xiaoyang
 * @version 1.0
 * @date 2023/08/14
 * @description
 */
public class RedisBlockingQueue<T> implements BlockingQueue<T>{

  private RedisTemplate<String, T> redisTemplate;

  private String queueKey;

  public RedisBlockingQueue(RedisTemplate<String, T> redisTemplate, String queueKey) {
    this.redisTemplate = redisTemplate;
    this.queueKey = queueKey;
  }

  @Override
  public void add(T t) {
    ListOperations<String, T> listOperations = redisTemplate.opsForList();
    listOperations.rightPush(queueKey, t);
  }

  @Override
  public T take() {
    ListOperations<String, T> listOperations = redisTemplate.opsForList();
    T t = listOperations.leftPop(queueKey);
    return t;
  }

  @Override
  public int size() {
    ListOperations<String, T> listOperations = redisTemplate.opsForList();
    Long size = listOperations.size(queueKey);
    if(size != null) {
      return size.intValue();
    }
    return 0;
  }
}
